﻿/*Reg读写Page*/
/*To do:更换Hex控件*/

using NovoDataBase;
using NovoSerDes;
using NovoSerDes.Funcs;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using NovoSerDes.Forms;

namespace NovoSerDesEva
{
    public partial class RegisterReadWrite : UIPage
    {
        private SerDesComm commDev;

        private List<int> regRWAddr = new List<int>();

        private ConfigState configSate;
        public ConfigState ConfigState
        {
            set { configSate = value; }
        }
        private AddressMeditor meditor;
        public AddressMeditor Meditor
        {
            get { return meditor; }
            set
            {
                meditor = value;
                meditor.AddressChanged += Meditor_AddressChanged;
            }
        }

        private void Meditor_AddressChanged(object sender, string newAddrss)
        {
            byte DevAddr = Convert.ToByte(newAddrss.Replace("0x", ""), 16);
            this.numericUpDown_ChipAddr.Value = DevAddr;
        }
        private USBDeviceMeditor usbDeveiceMetor;
        public USBDeviceMeditor UsbDeviceMetor
        {
            get { return usbDeveiceMetor; }
            set
            {
                usbDeveiceMetor = value;
                usbDeveiceMetor.USBDeviceChanged += usbDevice_DeviceChange;
            }
        }

        private void usbDevice_DeviceChange(object sender, SerDesComm newSerdesComm)
        {
            this.commDev = newSerdesComm;
        }


        public RegisterReadWrite(SerDesComm _commDev)
        {
            InitializeComponent();
            this.uiComboBox_SelectSerDes.SelectedItem = "Unkonwn";
            this.uiComboBox_IICMode.SelectedItem = IICMode.A16D32.ToString();
            commDev = _commDev;
            DpiSet();
        }

        public RegisterReadWrite(string name)
        {
            InitializeComponent();
            LogControl log = new LogControl();
            log.Dock = DockStyle.Fill;
            this.uiSplitContainer1.Panel2.Controls.Add(log);
            this.uiComboBox_SelectSerDes.SelectedItem = "Unkonwn";
            this.uiComboBox_IICMode.SelectedItem = IICMode.A16D32.ToString();
            commDev = InitSer(name);
            DpiSet();
        }

        public RegisterReadWrite(string name, AddressMeditor meditor)
        {
            InitializeComponent();
            this.uiComboBox_SelectSerDes.SelectedItem = "Unkonwn";
            this.uiComboBox_IICMode.SelectedItem = IICMode.A16D32.ToString();
            commDev = InitSer(name);
            this.meditor = meditor;
            DpiSet();
        }

        //别的文件（子页面）要想访问到这个文件（父页面）里的类的控件，通过构造函数传递引用

        private int RegPanelIndex = 0; //从0开始
        private List<RegWriteReadPanel> RegPanels = new List<RegWriteReadPanel>(); //访问先前创建的对象，方法是使用列表来存储所有的RegWriteReadPanel对象

        private void uiSymbolButton_AddRegPanel_Click(object sender, EventArgs e)
        {
            RegWriteReadPanel RegPanel = new RegWriteReadPanel(commDev, this.numericUpDown_ChipAddr, this.uiComboBox_IICMode);
            RegPanel.UsbDeviceMetor = usbDeveiceMetor;
            RegPanel.Text = "RegPanel" + RegPanelIndex.ToString("D");
            RegPanel.Name = RegPanel.Text;
            RegPanel.Left = 5;
            if(RegPanelIndex == 0)
            {
                RegPanel.Top = RegPanelIndex * (RegPanel.Height + 10);
            }
            else
            {
                RegWriteReadPanel lastPanel = RegPanels[RegPanelIndex - 1];
                RegPanel.Top = lastPanel.Top + (RegPanel.Height + 10);
            }
            panel2.Controls.Add(RegPanel);
            RegPanels.Add(RegPanel);
            RegPanelIndex++;
        }

        private bool AddRegPanel(RegWriteReadPanel RegPanel)
        {
            RegPanel.Text = "RegPanel" + RegPanelIndex.ToString("D");
            RegPanel.Name = RegPanel.Text;
            RegPanel.Left = 5;
            if (RegPanelIndex == 0)
            {
                RegPanel.Top = RegPanelIndex * (RegPanel.Height + 10);
            }
            else
            {
                RegWriteReadPanel lastPanel = RegPanels[RegPanelIndex - 1];
                RegPanel.Top = lastPanel.Top + (RegPanel.Height + 10);
            }
            panel2.Controls.Add(RegPanel);
            RegPanelIndex++;
            return true;
        }

        private void uiSymbolButton_DeleteRegPanel_Click(object sender, EventArgs e)
        {
            if(RegPanels.Count > 0)
            {
                RegWriteReadPanel lastPanel = RegPanels[RegPanels.Count - 1];
                panel2.Controls.Remove(lastPanel);
                RegPanels.Remove(lastPanel);
                //RegPanels.RemoveAt(RegPanels.Count - 1); //使用索引删除元素
                RegPanelIndex--;
            }
        }

        private void uiSymbolButton_ClearAll_Click(object sender, EventArgs e)
        {
            if(RegPanels.Count > 0)
            {
                foreach(var regpanel in RegPanels)
                {
                    regpanel.DecValue = 0;
                }
            }
        }

        private void uiSymbolButton_RegReadAll_Click(object sender, EventArgs e)
        {
            if (RegPanels.Count > 0)
            {
                foreach (var regpanel in RegPanels)
                {
                    regpanel.RegRead();
                }
            }
        }

        private void uiSymbolButton_RegWriteAll_Click(object sender, EventArgs e)
        {
            if (RegPanels.Count > 0)
            {
                foreach (var regpanel in RegPanels)
                {
                    regpanel.RegWrite();
                }
            }
        }

        private float GetDPI()
        {
            using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
            {
                float dpiX = graphics.DpiX;
                float dpiY = graphics.DpiY;
                return dpiX;
            }
        }

        private void DpiSet()
        {
            double dpi = GetDPI();
            double scale = dpi / 0.96;
            if (scale == 150 || scale == 125) //100% - 96 DPI;125% - 120 DPI;150% - 144 DPI;175% - 168 DPI;200% - 192 DPI
            {
                foreach (Control control in panel1.Controls)
                {
                    // 检查控件是否有Font属性，并且是否支持更改  
                    if (control.Font != null)
                    {
                        control.Font = new System.Drawing.Font("宋体", 8F);
                    }
                }

                foreach (Control control in uiPanel1.Controls)
                {
                    // 检查控件是否有Font属性，并且是否支持更改  
                    if (control.Font != null)
                    {
                        control.Font = new System.Drawing.Font("宋体", 8F);
                    }
                }

                foreach (Control control in uiPanel2.Controls)
                {
                    // 检查控件是否有Font属性，并且是否支持更改  
                    if (control.Font != null)
                    {
                        control.Font = new System.Drawing.Font("宋体", 8F);
                    }
                }
            }
        }

        private SerDesComm InitSer(string name)
        {
            if (MainForm.IniSerCommPairs.ContainsKey(name))
            {
                return (MainForm.IniSerCommPairs[name]);
            }
            else
            {
                //UIMessageDialog.ShowErrorDialog(FindForm(), "请选择CH347通道");
                return null;
            }
        }
        /// <summary>
        /// 初始化寄存器的读写地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="flag"></param>
        public void InitRegRWAddr(object sender, bool flag)
        {
            if (flag == true)//将所有的panel的regAddr保存起来
            {
                configSate = MainForm.ConfigState;
                regRWAddr.Clear();
                foreach (var regpanel in RegPanels)
                {
                    regRWAddr.Add(regpanel.RegAddr);
                }
                int index = -1;

                // 查找指定键的元素
                for (int i = 0; i < configSate.RegAddrPanel.Count; i++)
                {
                    if (configSate.RegAddrPanel[i].Key == this.Name)
                    {
                        index = i;
                        break;
                    }
                }

                // 如果找到了指定键的元素，则修改它的值
                if (index != -1)
                {
                    configSate.RegAddrPanel[index].Value = regRWAddr;
                }
                else
                {
                    KeyValueItem item = new KeyValueItem();
                    item.Key = this.Name;
                    item.Value = regRWAddr;
                    configSate.RegAddrPanel.Add(item);
                }
            }
            else
            {
                configSate = MainForm.ConfigState;



                // 查找指定键的元素
                for (int i = 0; i < configSate.RegAddrPanel.Count; i++)
                {
                    if (configSate.RegAddrPanel[i].Key == this.Name)
                    {
                        regRWAddr = configSate.RegAddrPanel[i].Value;
                        break;
                    }
                }


                foreach (var regAddr in regRWAddr)
                {
                    RegWriteReadPanel regWriteReadPanel = new RegWriteReadPanel(commDev, this.numericUpDown_ChipAddr, this.uiComboBox_IICMode);
                    regWriteReadPanel.RegAddr = regAddr;
                    AddRegPanel(regWriteReadPanel);
                    RegPanels.Add(regWriteReadPanel);
                }
            }

        }

        private void eOMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_EOM frm_EOM = new Form_EOM(commDev);
            frm_EOM.Show();
        }

        private void eFUSEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_EFUSE frm_EFUSE = new Form_EFUSE(commDev);
            frm_EFUSE.ShowDialog();
        }
    }
}
